package src.算法.插入排序;

public class insertSort {
    public static void sort(Comparable[] a){
        for (int i = 1; i < a.length; i++) {
            for (int k = i; k > 0 ; k--) {
                // 比较索引k处的值与k-1的值，如果k < k-1的值则交换
                if(greater(a[k-1],a[k])){
                    exch(a,k,k-1);
                }else {
                    break;
                }
            }
        }
    }
    // 比较前一个元素是否大于后一个元素
    private static boolean greater(Comparable a,Comparable b){
        int result = a.compareTo(b);
        return result>0;
    }
    // 数组元素i和j交换位置
    private static void exch(Comparable[] a,int i,int j){
        Comparable temp;
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}
